<template>
  <div>
    <h2>作业2</h2>
    标题：<input type="text" v-model="title" /> 价格：<input
      type="text"
      v-model="price"
    />
    <button @click="add">添加</button>
    <table border="1" width="500">
      <tr>
        <th>标题</th>
        <th>价格</th>
        <th>时间</th>
        <th>操作</th>
      </tr>
      <tr v-for="(item, index) in list" :key="index">
        <td>{{ item.title }}</td>
        <td>{{ item.price }}</td>
        <td>{{ item.time }}</td>
        <td><button>编辑</button><button @click="del(index)">删除</button></td>
      </tr>
    </table>
  </div>
</template>
<script>
export default {
  data() {
    return {
      list: [
        {
          title: "三国演义",
          price: 100,
          time: new Date(),
        },
        {
          title: "坏蛋是怎么炼成的",
          price: 50,
          time: new Date(),
        },
        {
          title: "渣男是怎么炼成的",
          price: 500,
          time: new Date(),
        },
        {
          title: "海王是怎么炼成的",
          price: 200,
          time: new Date(),
        },
        {
          title: "vue是怎么炼成的",
          price: 800,
          time: new Date(),
        },
      ],
      title: "",
      price: "",
    };
  },
  methods: {
    add() {
      this.list.push({
        title: this.title,
        price: this.price,
        time: new Date(),
      });
    },
    //添加
    del(index) {
      this.list.splice(index, 1);
    },
    //删除
  },
  created() {
    if (localStorage.getItem("list")) {
      this.list = JSON.parse(localStorage.getItem("list"));
    }
    //进入页面的时候 如果本地存储中有 就从本地存储中拿数据
  },
  watch: {
    list: {
      handler(newVal) {
        localStorage.setItem("list", JSON.stringify(newVal));
      },
      deep: true,
    },
    //通过监听 list的变化 只要一变就存在本地存储中
  },
};
</script>
<style lang="scss"></style>
